/* ===== selfmenu ===== ：个人中心 */
myApp.onPageInit('selfmenu', function (page) {
	console.log('selfmenu');
});

/* ===== selfbaseinfo ===== ：基本信息 编辑提交*/
myApp.onPageInit('selfbaseinfo', function (page) {
	console.log('selfbaseinfo');
	//添加按钮触发<input file>，选择图片
	$$('#selfbaseinfo .changeicon').touchend(function(){
		return $$("#selfbaseinfo .imgfile").click();
	});
	 //选择图片后触发change事件
	$$("#selfbaseinfo .imgfile").change(function(e){
		//图像被改变
		if($$('#selfbaseinfo .icon-container').hasClass('origin')){
			$$('#selfbaseinfo .icon-container').removeClass('origin');
		}
		//避免多次alert
    	var errorflag = false;
    	/*获取<input file>中的FileList对象或者dataTransfer对象的文件*/
    	/*<input file>标签中有mutiple属性，一次可以选择多张图保存到<input file>中*/
        var files = e.target.files||e.dataTransfer.files;
        for(var i=0;i<files.length;i++){
        	//检查图片大小和类型
             if(files[i]){
            	 console.log(files[i].type);
            	 var filesize=Math.round(files[i].size/1024/1024*100)/100;//单位MB
                 if(filesize>5){
                	 if(!errorflag){
                		 ajaxfail("图片大小不要超过5M");
                		 errorflag=true;
                	 }                 	                 	 
                 }else{
                	 /*为此次添加的文件创建base64码*/
                	 var reader = new FileReader();
                     reader.readAsDataURL(files[i]);
                     reader.onload=function(){
                        //生成缩略图
                    	$$("#selfbaseinfo .icon-container").attr('src',this.result);                     
                     }
                 }                                  
            }                
        }
	});
	
    $$('#selfbaseinfo .selfinfo_submit').click(function(){
        var userFamily = $$('#selfbaseinfo input[name="userFamily"]').val();
        var userName = $$('#selfbaseinfo input[name="userName"]').val();
        var userGender = $$('#selfbaseinfo select[name="userGender"]').val();
        var introduction = $$('#selfbaseinfo textarea[name="introduction"]').val();
        var userAge = $$('#selfbaseinfo select[name="userAge"]').val();
        var nationality = $$('#selfbaseinfo input[name="nationality"]').val();
        var resideCity = $$('#selfbaseinfo input[name="resideCity"]').val();
        var resideTime = $$('#selfbaseinfo select[name="resideTime"]').val();
        //判断头像是否改变
        if(!$$('#selfbaseinfo .icon-container').hasClass('origin')){
        	var userIcon = $$('#selfbaseinfo .icon-container').attr('src');
        }
        
        //console.log(userIcon,userFamily,userName,userAge,userGender,nationality,resideCity,resideTime,introduction);return;
        $$.ajax({
            url:url_post_selfbaseinfo_submit,
            dataType:'json',
            method:"POST",
            xhrFields:{withCredentials:true},
            data: {
                userFamily:userFamily,
                userName:userName,
                userGender:userGender,
                introduction:introduction,
                userAge:userAge,
                nationality:nationality,
                resideCity:resideCity,
                resideTime:resideTime,
                userIcon:userIcon
            }, 
            success:function (ajaxresult) {
                if(ajaxresult.code==1){
                    myApp.alert("修改成功");
                    mainView.router.back();
                }else{
                    ajaxfail(ajaxresult.msg);
                }
            },
        });   	
    });
});

/* ===== selfID ===== ：我的身份*/
myApp.onPageInit('selfID', function (page) {
	console.log('selfID');
    var pickerDevice = myApp.picker({
        input: '.selfID_role',
        cols: [
            {
                textAlign: 'center',
                values: ['留学生', '华人华侨', '外国人']
            }
        ]
    });
    $$('#selfID .selfID_submit').click(function(){
        var identityName = $$("#selfID input[name='role']").val();
        var school = $$("#selfID input[name='school']").val();
        var major = $$("#selfID input[name='major']").val();
        var job = $$("#selfID input[name='job']").val();
    	$$.ajax({
            url:url_post_checkidentity,
            data:{
                'identityName':identityName,
                'school':school,
                'major':major,
                'job':job,
                //!!!!!!!!!!!!!!!!!!!!!!!!放在uploadpic的页面提交
                'identity_pic':'',
                'certificate_pic':'',
            },
            dataType:'json',
            method:"POST",
            success:function(ajaxresult){
                if(ajaxresult.code==1){
                    myApp.alert("修改成功！");
                }else{
                    ajaxfail(ajaxresult.msg);
                }

            }
        });
    });
});

/* ===== uploadIDpaper =====：上传ID IMG */
myApp.onPageInit('uploadIDpaper', function (page) {
    $$("#uploadIDpaper .upimg").on('touchend',function(){
        return $$('#uploadIDpaper input[type="file"]').click();
    });
    //!!!!!!!!!!!!!!!!!提交图片
    $$("#uploadIDpaper input[type='file']").on('change',function(e){
        var files = e.target.files||e.dataTransfer.files;
        console.log(files);
        if(files[0]){
            var reader = new FileReader();
            reader.readAsDataURL(files[0]);
            reader.onload=function(){
               var result=$$("#uploadIDpaper .result");
                //显示文件  
                result.html('<img src="' + this.result +'" style="width:80%;"/>');
            }                
        }
    });
    // var files = $$('#scoperemark .imgfile').files;
});

/* ===== uploadCareerpaper =====：上传Career IMG */
myApp.onPageInit('uploadCareerpaper', function (page) {
    $$("#uploadCareerpaper .upimg").on('touchend',function(){
        return $$('#uploadCareerpaper input[type="file"]').click();
    });
    //!!!!!!!!!!!!!!!!!提交图片
    $$('#uploadCareerpaper input[type="file"]').on('change',function(e){
        var files = e.target.files||e.dataTransfer.files;
        console.log(files);
        if(files[0]){
            var reader = new FileReader();
            reader.readAsDataURL(files[0]);
            reader.onload=function(){
               var result=$$("#uploadCareerpaper .result");
                //显示文件  
                result.html('<img src="' + this.result +'" style="width:80%;"/>');
            }                
        }
    });
});

/* ===== myremark ===== ：我的评论*/
myApp.onPageInit('myremark', function (page) {
    console.log('myremark');
    var completed_page = 1;
    var uncomplete_page = 1;
    var limit = 10;
    $$('#myremark .tab .row a').click(function(){
        $$('#myremark .tab .col-50_active').removeClass('col-50_active');
        myApp.attachInfiniteScroll($$('#myremark .infinite-scroll'));
        $$(this).parent().addClass('col-50_active');
    });

    $$("#myremark .remark").on("click",function(){
        var id = $$(this).data("id");
        mainView.router.load({
            "url":"remark.html",
            "context":{"id":id}
        }); 
    });
    $$('#myremark .infinite-scroll').on('infinite', function () {
        console.log("scroll");
        $$('#myremark .infinite-scroll-preloader').show();
        if (loading) return;
        loading = true;
        setTimeout(function () {
            loading = false;
            if($$('#myremark .tab .col-50_active').attr("name")=='completed'){
                completed_page++;
                $$.getJSON(url_get_mycomments, {
                    size:limit,// 每页显示数量
                    page:completed_page,// 页码
                    iscomment :1
                }, function (ajaxresult) {
                    if(ajaxresult.code==1){
                        if(ajaxresult.data != false){
                            var data_myremarklist = ajaxresult.data.data;
                            var html_myremarklist = myApp.myremarklist_1Template(data_myremarklist);
                            $$('#myorder #completed ul').append(html_myremarklist);
                        }else{
                            myApp.detachInfiniteScroll($$('#myremark .infinite-scroll'));
                            $$('#myremark .infinite-scroll-preloader').hide();
                            return;
                        }
                    }else{
                        ajaxfail(ajaxresult.msg);
                    }
                });
            }else{
                uncomplete_page++;
                $$.getJSON(url_get_mycomments, {
                    size:limit,// 每页显示数量
                    page:uncomplete_page,// 页码
                    iscomment :0// (1 有效单 0 退款单)
                }, function (ajaxresult) {
                    if(ajaxresult.code==1){
                        if(ajaxresult.data != false){
                            var data_myremarklist = ajaxresult.data.data;
                            var html_myremarklist = myApp.myremarklist_2Template(data_myremarklist);
                            $$('#myremark #uncomplete ul').append(html_myremarklist);

                        }else{
                            myApp.detachInfiniteScroll($$('#myremark .infinite-scroll'));
                            $$('#myremark .infinite-scroll-preloader').hide();
                            return;
                        }
                    }else{
                        ajaxfail(ajaxresult.msg);
                    }
                });
            }
      }, 1000);
    }); 
});

/* ===== remark =====：写评语 */
myApp.onPageInit('remark',function(page){
    var filelist = [];
    $$("#remark .guider_remark img").on('touchend',function(){
        var guider_remark_dom = $$("#remark .guider_remark img");
        var index;
        for(var i=0;i<guider_remark_dom.length;i++){
            if(this == guider_remark_dom[i] ){
                index = i;
            }
        }
        for(var j=0;j<index+1;j++){
            $$(guider_remark_dom[j]).addClass("active");
        }
    });
    $$("#remark .line_remark img").on('touchend',function(){
        var guider_remark_dom = $$("#remark .line_remark img");
        var index;
        for(var i=0;i<guider_remark_dom.length;i++){
            if(this == guider_remark_dom[i] ){
                index = i;
                console.log(i);
            }
        }
        for(var j=0;j<index+1;j++){
            $$(guider_remark_dom[j]).addClass("active");
        }
        // $$(this)
    });
    $$("#remark .remark_photo").on('touchend',function(){
        return $$("#remark .imgfile").click();
    });
    $$("#remark .imgfile").on('change',function(e){
        var files = e.target.files||e.dataTransfer.files;
        if(filelist){
            for(var i=0;i<files.length;i++){
                 if(files[i]){
                    filelist.push(files[i]);
                }                
            }
        }else{
            filelist = files;
        }
        console.log(files,filelist);
        for(var i=0;i<files.length;i++){
            if(files[i]){
                var reader = new FileReader();
                reader.readAsDataURL(files[i]);
                reader.onload=function(){
                   var result=$$("#remark .photo");
                    //显示文件  
                    result.html('<div class="col-25" style="text-align:left;width: calc(100%/4);"><img src="' + this.result +'" style="width:80%;"/></div>'+ result.html());
                    $$("#remark .remark_photo").on('touchend',function(){
                        console.log("a");
                        return $$("#remark .imgfile").click();
                    });
                    $$("#remark .imgfile").val(null);
                }                
            }
        }        
    });
    $$("#remark .remark_submit").on("click",function(){
        var orderNo = $$(this).data("id");
        var comments = $$("#remark textarea[name='comments']").val();
        var guider_score = $$("#remark .guider_remark img.active").length;
        var track_score = $$("#remark .line_remark img.active").length;
        $$.ajax({
            url:url_post_addcomment,
            data:{
                'guider_score':guider_score,
                'track_score':track_score,
                'orderNo':orderNo,
                'comments':comments,
                '<input type="file" name="comments_pic[]">':filelist
            },
            dataType:'json',
            method:"POST",
            success:function(ajaxresult){
                if(ajaxresult.code==1){
                    myApp.alert("评论成功！");
                }else{
                    ajaxfail(ajaxresult.msg);
                }

            }
        });
    });
    
	var actionSheetButtons = [
        [
            {
                text: '相册',
                onClick: function () {
                   
                }
            },
            {
                text: '拍照',
                //color: 'red',
                onClick: function () {
                    
                }
            },
        ],
        [
            {
                text: '取消',
                bold: true
            }
        ]
    ];
    $$('#remark .process').on('click', function (e) {
        myApp.actions(actionSheetButtons);
    });	
});

/* ===== selfmsg =====：我的私信 链接传输other信息 */
myApp.onPageInit('selfmsg', function (page) {
	console.log('selfmsg');
    // !!!!!!!!!!!!page 从0开始？
    // 加载flag
    var loading = false;
    var page = 1;
    var limit = 10;
    $$('#selfmsg .msgitem').on('click',function(){
        var rev_id = $$(this).data('id');
        $$.getJSON(url_get_chat, {
            rev_id:rev_id,// 接收对象id
            page:1,
        }, function (ajaxresult) {
            if(ajaxresult.code==1){
                console.log(ajaxresult.data);
                mainView.router.load({
                    "url":"msg.html",
                    "context":ajaxresult.data
                }); 
            }else{
                ajaxfail(ajaxresult.msg);
            }
        });
    });
    $$('#selfmsg .infinite-scroll').on('infinite', function () {
        $$('#selfmsg .infinite-scroll-preloader').show();
        if (loading) return;
        loading = true;
        setTimeout(function () {
            loading = false;
            page++;
            // 生成新条目的HTML
            $$.ajax({
                method:'POST',
                url:url_post_mymsg,
                data: {
                    page:page,// 页码
                },
                dataType:'json',
                success: function (ajaxresult) {
                    if(ajaxresult.data != false){
                        var data_selfmsg = ajaxresult.data;            
                        var html_selfmsgcontent = myApp.selfMsgTemplate(data_selfmsg);
                        $$('#msg .div_msgcontent').append(html_selfmsgcontent);
                    }else{
                        myApp.detachInfiniteScroll($$('#selfmsg .infinite-scroll'));
                        $$('#selfmsg .infinite-scroll-preloader').hide();
                        return;
                    }
                },
            });
        }, 1000);
    });
});

/* ===== msg =====：私信 */
myApp.onPageInit('msg', function (page) {
	console.log('msg');
    var facetext = [
        "#呵呵#", "#哈哈#","#吐舌#", "#啊#","#酷#","#怒#", "#开心#",
        "#汗#", "#泪#", "#黑线#","#鄙视#", "#不高兴#", "#真棒#",
        "#钱#", "#疑问#", "#阴脸#", "#吐#", "#咦#", "#委屈#",
        "#花心#", "#呼~#", "#笑脸#", "#冷#", "#太开心#", "#滑稽#",
        "#勉强#", "#狂汗#", "#乖#","#睡觉#", "#惊哭#", "#生气#",
        "#惊讶#", "#喷#", "#爱心#", "#心碎#", "#玫瑰#", "#礼物#",
        "#彩虹#", "#星星月亮#", "#太阳#", "#钱币#", "#灯泡#",
        "#茶杯#", "#蛋糕#", "#音乐#","#haha#","#胜利#","#大拇指#",
        "#弱#","#OK#"
    ];
    var _html='';
    var html='';
    for(var k=1;k<51;k++){
        var picurl = "http://api.wayatrip.com/resource/skin/face/tieba/"+ k.toString() + ".png";
        _html = _html +  '<div class="col-10 emoji" data-num="'+ k.toString() +'"><img src="'+ picurl + '"></div>';
        if(k%10==0){
            html = html + '<div class="row">'+_html+'</div>';
            _html = '';
        }
    }
    $$("#msg .emojiimg").html(html);
    $$("#msg .emoji_toggle").on("click",function(){
        $$("#msg .emojiimg").toggleClass("hide");
    });
    $$("#msg .emoji").on("click",function(){
        var emojinum = $$(this).data("num");
        $$("#msg .msg").val($$("#msg .msg").val()+facetext[emojinum]);
    });
	// var user_name = global_login_user_name;
	// var user_id = global_login_user_id;
	// var other_name = '';
	// var other_id = '';
    //获取chat list
    // $$.getJSON(url_get_chat, {
    //     rev_id:12,// 接收对象id
    //     page:1,
    // }, function (ajaxresult) {
    //     if(ajaxresult.code==1){
    //         var data_msg = ajaxresult.data;            
    //         var html_msgcontent = myApp.msgTemplate(data_msg);
    //         $$('#msg .div_msgcontent').html(html_msgcontent);
    //     }else{
    //         ajaxfail(ajaxresult.msg);
    //     }
    // });
	//	发送信息
	$$('#msg .send-message').click(function(){		
        var text = $$("#msg .msg").val();
        var rev_id = $$(this).data("rev_id")
        $$.getJSON(url_post_addchat, {
            rev_id:rev_id,// 接收对象id
            text:text// 聊天信息
        }, function (ajaxresult) {
            if(ajaxresult.code==1){
                $$.getJSON(url_get_chat, {
                    rev_id:12,// 接收对象id
                    page:1,
                }, function (ajaxresult) {
                    if(ajaxresult.code==1){       
                        mainView.router.reloadPage({
                            "url":"msg.html",
                            "context":ajaxresult.data
                        }); 
                    }else{
                        ajaxfail(ajaxresult.msg);
                    }
                });
            }else{
                ajaxfail(ajaxresult.msg);
            }
        });
	});
});

/* ===== accountsetting ===== ：帐户设置*/
myApp.onPageInit('accountsetting', function (page) {
    console.log("accountsetting");
    $$("#accountsetting .changepwd").on("click",function(){
        $$.getJSON(url_post_editpassword, {}, function (ajaxresult) {
            if(ajaxresult.code==1){
                console.log(ajaxresult.data);
                mainView.router.load({
                    "url":"changepwd.html",
                    "context":ajaxresult.data
                });                     
            }else{
                ajaxfail(ajaxresult.msg);
            }
        });
    });
});

/* ===== telverify =====：telverify */
myApp.onPageInit('telverify',function(page){
    //验证码
    $$("#telverify .telcode").on("click",function(){
        var tel = $$("#telverify input[name='tel']").val();
        // !!!!!!!!!!!!!!!!!areacode？
        var areacode = $$(this).data("areacode");
        $$.ajax({
            url:url_get_telcode, 
            method:"POST",
            data:{
                utype:global_login_role, //类型(TOURIST,GUIDER)
                areaCode:areacode,// 区号
                phoneNum:tel
            },
            dataType:'json',
            success:function (ajaxresult) {
                //获取数据
                if(ajaxresult.code==1){
                    myApp.alert("验证码已发送，请注意查收。");                   
                }else{
                    ajaxfail(ajaxresult.msg);
                }
            },
        });
    });

    $$('#telverify .submit').click(function(){
        var tel = $$("#telverify input[name='tel']").val();
        var telcode = $$("#telverify input[name='telcode']").val();
        $$.ajax({
            url:url_post_validatemobile,
            method:"POST",
            data: {
                phoneNum:tel,
                areaCode:'',
                securimage_code_value:telcode,
            },
            dataType:'json',
            success: function (ajaxresult) {
                //获取数据
                if(ajaxresult.code == 1){
                    myApp.alert("绑定成功");
                }else{
                    ajaxfail(ajaxresult.msg);
                }
            },
        });
    }); 
});

/* ===== emailverify =====：emailverify */
myApp.onPageInit('emailverify',function(page){
    // 获取验证码
    $$('#emailverify .emailcode').click(function(){
        var email = $$("#emailverify input[name='email']").val();
        $$.ajax({
            url:url_post_sendemailcode,
            method:"POST",
            data: {
                email:email,
            },
            dataType:'json',
            success: function (ajaxresult) {
                //获取数据
                if(ajaxresult.code == 1){
                    myApp.alert("验证码发送成功，请注意查收");
                }else{
                    ajaxfail(ajaxresult.msg);
                }
            },
        });
    });
    //提交绑定
    $$('#emailverify .submit').click(function(){
        var email = $$("#emailverify input[name='email']").val();
        var emailcode = $$("#emailverify input[name='emailcode']").val();
        $$.ajax({
            url:url_post_validateemail,
            method:"POST",
            data: {
                email:email,
                securimage_code_value:emailcode,
            },
            dataType:'json',
            success: function (ajaxresult) {
                //获取数据
                if(ajaxresult.code == 1){
                    myApp.alert("绑定成功");
                }else{
                    ajaxfail(ajaxresult.msg);
                }
            },
        });
    }); 
});

/* ===== changpwd =====：changpwd */
myApp.onPageInit('changpwd',function(page){
    //验证码
    $$("#changpwd .telcode").on("click",function(){
        var tel = $$(this).data("phonenum")?$$(this).data("phonenum"):$$("#changpwd input[name='tel']").val();
        // !!!!!!!!!!!!!!!!未绑定时areacode？
        var areacode = $$(this).data("areacode");
        $$.ajax({
            url:url_get_telcode, 
            method:"POST",
            data:{
                utype:global_login_role, //类型(TOURIST,GUIDER)
                areaCode:areacode,// 区号
                phoneNum:tel
            },
            dataType:'json',
            success:function (ajaxresult) {
                //获取数据
                if(ajaxresult.code==1){
                    myApp.alert("验证码已发送，请注意查收。");                   
                }else{
                    ajaxfail(ajaxresult.msg);
                }
            },
        });
    });
    //修改
    $$('#changpwd .submit').click(function(){
        var tel = $$(this).data("phonenum")?$$(this).data("phonenum"):$$("#changpwd input[name='tel']").val();
        // 未绑定时areacode？
        var areacode = $$(this).data("areacode");
        var pwd = $$("#changpwd input[name='pwd']").val();
        var repwd = $$("#changpwd input[name='repwd']").val();
        var code = $$("#changpwd input[name='code']").val();
        $$.ajax({
            url:url_post_editpassword,
            method:"POST",
            data: {
                password:pwd,//密码
                re_password:repwd,//确认密码
                phoneNum:tel,//手机号
                areaCode:areacode,//区域号
                securimage_code_value:code,//验证码
            },
            dataType:'json',
            success: function (ajaxresult) {
                //获取数据
                if(ajaxresult.code == 1){
                    myApp.alert("密码修改成功");
                    mainView.router.load({
                        "url":"login.html"
                    }); 
                }else{
                    ajaxfail(ajaxresult.msg);
                }
            },
        });
    });
});